import Vue from 'vue'
import Router from 'vue-router'
import routes from './router'
import store from '@/store/index'
import cookies from '@/utils/store/cookies'
import setting from '@/setting'
// fix vue-router NavigationDuplicated
const routerPush = Router.prototype.push
Router.prototype.push = function push(location: any) {
    return (routerPush as any).call(this, location).catch((error: any) => error)
}
const routerReplace = Router.prototype.replace
Router.prototype.replace = function replace(location: any) {
    return (routerReplace as any).call(this, location).catch((err: any) => err)
}

Vue.use(Router)

// 导出路由 在 main.js 里使用
const router = new Router({
    routes
})

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
    // 验证当前路由所有的匹配中是否需要有登录验证的
    if (to.matched.some(r => r.meta.noAuth)) {
        // 不需要身份校验 直接通过
        next()
    } else {
        // 这里暂时将cookie里是否存有token作为验证是否登录的条件
        // 请根据自身业务需要修改
        const token = cookies.get(setting.requestConfig.tokenName);
        if (token && token !== 'undefined') {
            next()
        } else {
            // 退出登录，清空数据
            store.dispatch('account/logoutTodo')
        }
    }
})

export default router